import { AntDraggableModal } from "@/hy_dev_lib/src";
import { IModalProps } from "@/hy_dev_lib/src/components/AntDraggableModal";
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row } from "antd";
import { useEffect } from "react";

const EditOptions = (props: IModalProps) => {
    const { open, setOpen } = props
    const { form: configForm } = open || {}
    const [form] = Form.useForm()

    useEffect(() => {
        if (!open) return
        const originData = configForm.getFieldValue("options")
        if (!originData?.length) return form.setFieldsValue({
            options: [{ nr: "" }]
        })
        form.setFieldsValue({
            options: configForm.getFieldValue("options")?.map((item: string) => ({ nr: item }))
        })
    }, [open])

    const onOk = () => {
        onCancel()
        configForm.setFieldsValue({
            options: form.getFieldValue("options")?.map((item: { nr: string }) => item.nr)
        })
    }

    const onCancel = () => {
        setOpen(null)
    }

    return <AntDraggableModal
        open={!!open}
        onCancel={onCancel}
        onOk={onOk}
        title="编辑选项"
    >
        <Form form={form}>
            <Form.List name="options">
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name }) => (
                            <Row key={key} wrap justify="space-between">
                                <Col span={22}>
                                    <Form.Item
                                        name={[name, 'nr']}
                                        // label="内容"
                                        rules={[{ required: true, message: '' }]}
                                    >
                                        <Input placeholder="请输入选项内容" />
                                    </Form.Item>
                                </Col>
                                <Col span={1} style={{ lineHeight: "32px" }}>
                                    <MinusCircleOutlined className="danger" onClick={() => remove(name)} />
                                </Col>
                            </Row>
                        ))}
                        <Form.Item style={{ marginBottom: 0 }}>
                            <Button className="primary-outline-btn" onClick={() => add()} block icon={<PlusOutlined />}>
                                添加选项
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
        </Form>
    </AntDraggableModal>
}

export default EditOptions
